<template>
  <div class="app-container">

    <el-row :gutter="20">

      <!--分类数据-->
      <el-col :span="4" :xs="24">
        <el-card style="border-radius: 10px">
          <div class="head-container">
            <el-input
                v-model="projectTypeName"
                placeholder="请输入分类名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
                :data="projectTypeOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                default-expand-all
                @node-click="handleNodeClick"
            />
          </div>
        </el-card>
      </el-col>

      <!--项目数据-->
      <el-col :span="20" :xs="24">
        <el-card style="border-radius: 10px">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="项目编码" prop="projectCode">
              <el-input
                v-model="queryParams.projectCode"
                placeholder="请输入项目编码"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input
                v-model="queryParams.projectName"
                placeholder="请输入项目名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card style="border-radius: 10px">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['pc:project:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                  type="info"
                  icon="el-icon-upload2"
                  size="mini"
                  @click="handleImport"
                  v-hasPermi="['pc:project:import']"
              >导入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['pc:project:export']"
              >导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="projectList">
            <el-table-column label="项目编码" align="center" prop="projectCode">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="text"
                    @click="handleView(scope.row)"
                    v-hasPermi="['pc:project:query']"
                >{{scope.row.projectCode}}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="项目名称" align="center" prop="projectName" />
            <el-table-column label="项目类型编码" align="center" prop="projectTypeCode" />
            <el-table-column label="项目类型名称" align="center" prop="projectTypeName" />
            <el-table-column label="是否启用" align="center" prop="enableFlag">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.enableFlag"
                  active-value="Y"
                  inactive-value="N"
                  @change="handleChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="负责人" align="center" prop="principal" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['pc:project:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['pc:project:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-col>
    </el-row>


    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目编码" prop="projectCode">
              <el-input v-model="form.projectCode" readonly="readonly" maxlength="64" v-if="optType === 'view'"/>
              <el-input v-model="form.projectCode" placeholder="请输入项目编码" maxlength="64" v-else/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName"  maxlength="255" readonly="readonly" v-if="optType === 'view'" />
              <el-input v-model="form.projectName" placeholder="请输入项目名称" maxlength="255" v-else/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="projectTypeId">
              <treeselect
                  v-model="form.projectTypeId"
                  :options="projectTypeOptions"
                  :normalizer="normalizer"
                  disabled
                  v-if="optType === 'view'"
              />
              <treeselect
                  v-model="form.projectTypeId"
                  :options="projectTypeOptions"
                  :normalizer="normalizer"
                  placeholder="请选择所属分类"
                  v-else
                  :disable-branch-nodes='true'
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="principal">
              <el-input v-model="form.principal" placeholder="请输入负责人" readonly>
                <el-button
                    slot="append"
                    @click="handleSelectUser"
                    icon="el-icon-search"
                    v-if="optType !== 'view'">
                </el-button>
              </el-input>
              <UserSelect ref="userSelect" @onSelected="onUserSelected" ></UserSelect>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" readonly v-if="optType === 'view'"></el-input>
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" v-else></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="optType !== 'view'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 项目导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的设备数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
              type="primary"
              :underline="false"
              style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate"
          >下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject } from "@/api/mes/pc/project";
import { listProjectType } from "@/api/mes/pc/projectType";
import { genCode } from "@/api/system/autocode/rule"
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import UserSelect from "@/components/userSelect/single.vue";
import { getUserProfile } from "@/api/system/user";

export default {
  name: "Project",
  components: { Treeselect, UserSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目信息表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectCode: null,
        projectName: null,
        projectTypeId: null,
        projectTypeCode: null,
        projectTypeName: null,
        enableFlag: null,
        principal: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectCode: [
          { required: true, message: "项目编码不能为空", trigger: "blur" }
        ],
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        projectTypeId: [
          { required: true, message: "所属分类不能为空", trigger: "blur" }
        ],
        principal: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
      },
      // 项目类型名称
      projectTypeName: undefined,
      // 项目类型树数据
      projectTypeOptions: [],
      // 项目类型树属性
      defaultProps: {
        children: "children",
        label: "projectTypeName"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/pc/project/importData"
      },
      // 显隐开关
      optType: undefined,
      // 当前登录用户
      user: null,

    };
  },
  watch: {
    // 根据项目分类名称筛选分类树
    projectTypeName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getUser();
  },
  methods: {
    /** 查询项目信息列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        projectCode: null,
        projectName: null,
        projectTypeId: null,
        projectTypeCode: null,
        projectTypeName: null,
        enableFlag: 'Y',
        principal: null,
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      if (this.queryParams.projectTypeId != 0) {
        this.form.projectTypeId = this.queryParams.projectTypeId;
      }
      genCode('PC_PROJECT_CODE').then(response =>{
        this.form.projectCode = response;
      });
      this.form.principal = this.user.nickName;
      this.optType = "add";
      this.open = true;
      this.title = "添加项目信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const projectId = row.projectId || this.ids
      getProject(projectId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目信息";
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.projectId != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$modal.confirm('是否确认删除项目信息编号为"' + projectIds + '"的数据项？').then(function() {
        return delProject(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pc/project/export', {
        ...this.queryParams
      }, `项目信息_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "项目导入";
      this.upload.open = true;
    },
    /** 是否启用 */
    handleChange(row) {
      updateProject(row).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.projectName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.projectTypeId = data.projectTypeId;
      this.handleQuery();
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      this.getTreeselect();
      const projectId = row.projectId || this.ids;
      getProject(projectId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看项目信息";
        this.optType = "view";
      });
    },
    /** 查询项目类型下拉树结构 */
    getTreeselect() {
      listProjectType().then(response => {
        this.projectTypeOptions = [];
        const data = this.handleTree(response.data, "projectTypeId", "parentTypeId")[0];
        this.projectTypeOptions.push(data);
      })
    },
    /** 转换项目类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.projectTypeId,
        label: node.projectTypeName,
        children: node.children
      };
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('pc/project/importTemplate', {
      }, `项目信息_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>"
          + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 选择用户点击
    handleSelectUser(){
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj){
      if(obj !== undefined && obj !== null){
        this.form.principal = obj.nickName;
      }
    },
    // 获取登录用户
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },


  }
};
</script>
